package cn.hnshxy.ldf;

import java.sql.*;
import java.util.*;

public class DbHelper {
	private ResultSet rs=null;
	private PreparedStatement ps=null;
	private Connection cn=null;
	static {
		System.out.println("加载驱动~");
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public List<Map<String,Object>> executeQuery(String sql, Object...params) {
		try {
			cn = getConnection();
			ps = cn.prepareStatement(sql);
			for(int i=0;i<params.length;++i) {
				ps.setObject(i+1, params[i]);
			}
			rs = ps.executeQuery();
			return toList(rs);
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			free();
		}
		return null;
	}
	public int executeUpdate(String sql, Object...params) {
		try {
			cn = getConnection();
			ps = cn.prepareStatement(sql);
			for(int i=0;i<params.length;++i) {
				ps.setObject(i+1, params[i]);
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			free();
		}
		return -1;
	}
	private void free() {
		System.out.println("释放资源~");
		try {
			if(rs!=null && !rs.isClosed())rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(ps!=null && !ps.isClosed())ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(cn!=null && !cn.isClosed())cn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		rs=null;
		ps=null;
		cn=null;
	}
	private List<Map<String, Object>> toList(ResultSet rs) throws SQLException {
		List<Map<String, Object>>list=new ArrayList<>();
		ResultSetMetaData md = rs.getMetaData();//元数据
		int count = md.getColumnCount();
		while(rs.next()) {
			Map<String, Object>fields=new HashMap<>();
			for(int i=1;i<=count;++i) {
				String label = md.getColumnLabel(i);
				Object value = rs.getObject(label);
				fields.put(label, value);
			}
			list.add(fields);
		}
		return list;
	}

	private Connection getConnection() throws SQLException {
		return DriverManager.getConnection("jdbc:mysql://localhost:3306/db?serverTimezone=PRC","root","12qwas");
	}
	public static void main(String[] args) throws SQLException {
		DbHelper db = new DbHelper();
		List<Map<String, Object>> list = db.executeQuery("select t1 as 题目 from ku limit ?", 2);
		for(int i=0;i<list.size();++i) {
			Map<String, Object> map = list.get(i);
			Object t = map.get("题目");
			System.out.println(t);
		}
		System.out.println("Over");
	}
}
